import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import store from '@/store'

// push 和 replace 方法重写
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve || reject) {
    originalPush.call(this, location, resolve, reject)
  } else {
    originalPush.call(this, location, () => { }, () => { })
  }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve || reject) {
    originalReplace.call(this, location, resolve, reject)
  } else {
    originalReplace.call(this, location, () => { }, () => { })
  }
}

const routes = [
  {
    path: '/',
    redirect: '/Home'
  },
  {
    //首页
    path: '/Home',
    name: 'Home',
    component: () => import('@/views/Home'),
    meta: { show: true }
  },
  {
    //登录
    path: '/Login',
    name: 'Login',
    component: () => import('@/components/header/login/Login'),
    meta: { show: false }
  },
  {
    //注册
    path: '/Register',
    name: 'Register',
    component: () => import('@/components/header/register/Register'),
    meta: { show: false }
  },
  {
    //搜索
    //如果params参数占位但是不传，URL会有问题
    //如何指定paeams参数可传可不传： 在配置路由的时候，在占位的后面加上一个 ？ 
    path: '/Search/:keyword?',//params参数占位
    name: 'Search',
    component: () => import('@/components/header/search/Search'),
    meta: { show: true }
  },
  {
    //商品详情
    path: '/Detail/:skuId',
    name: 'Detail',
    component: () => import('@/components/detail/Detail'),
    meta: { show: true }
  },
  {
    //添加购物车
    path: '/AddCartSuccess',
    name: 'AddCartSuccess',
    component: () => import('@/components/addCartSuccess/AddCartSuccess'),
    meta: { show: true }
  },
  {
    //购物车
    path: '/ShopCart',
    name: 'ShopCart',
    component: () => import('@/components/shopCart/ShopCart'),
    meta: { show: true }
  },
  {
    //结算购物车
    path: '/Trade',
    name: 'Trade',
    component: () => import('@/components/trade/Trade'),
    meta: { show: true },
    //路由独享守卫
    beforeEnter: (to, from, next) => {
      if(from.path == '/ShopCart') {
        next()
      } else {
        next(false)
      }
    }
  },
  {
    //支付
    path: '/Pay',
    name: 'Pay',
    component: () => import('@/components/Pay/Pay'),
    meta: { show: true },
    //路由独享守卫
    beforeEnter: (to, from, next) => {
      if (from.path == '/Trade') {
        next()
      } else {
        next(false)
      }
    }
  },
  {
    //支付
    path: '/PaySuccess',
    name: 'PaySuccess',
    component: () => import('@/components/paySuccess/PaySuccess'),
    meta: { show: true }
  },
  {
    //个人中心
    path: '/Center',
    name: 'Center',
    component: () => import('@/components/center/Center'),
    meta: { show: true },
    children:[
      {
        path: 'MyOrder',
        name: 'MyOrder',
        component: () => import('@/components/center/myOrder/MyOrder'),
      },
      {
        path: 'GroupOrder',
        name: 'GroupOrder',
        component: () => import('@/components/center/groupOrder/GroupOrder'),
      },
      {
        path: '/Center',
        redirect:'/Center/MyOrder'
      }
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  //滚动行为
  scrollBehavior(to, from, savedPosition) {
    //y:0 代表滚动在最上方
    return { y: 0 }
  }
})

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  // to and from are both route objects. must call `next`.
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  //用户已登录
  if (token) {
    //用户已登录就不能去Login
    if (to.path == '/Login' || to.path == '/Register') {
      //去home
      next('/')
    } else {
      //如果用户名已存在
      if (name) {
        //放行
        next()
      } else {
        //没有用户信息，派发action
        try {
          //获取用户信息
          await store.dispatch('getUserInfo')
          //放行
          next()
        } catch (error) {
          //如果token失效，重新登录
          //清除token
          await store.dispatch('userLogout')
          next('/Login')
        }
      }
    }
  } else {
    //未登录
    let toPath = to.path;
    if(toPath.indexOf('/Trade') != -1 || toPath.indexOf('/Pay') != -1 || toPath.indexOf('/center') != -1) {
      next('/Login?redirect='+toPath)
    } else {
      next()
    }
  }
})

export default router
